<template>
  <div>
    <!--  :model="form" -->
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="spuList.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spuList.tmId">
          <el-option
            :label="trademark.tmName"
            :value="trademark.id"
            v-for="trademark in trademarkList"
            :key="trademark.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          :rows="4"
          v-model="spuList.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          ref="upload"
          :file-list="spuImageList || []"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="showText"
          v-model="saleAttrName"
          :disabled="saleAttrList.length === 0"
        >
          <el-option
            :label="saleAttr.name"
            :value="saleAttr.name"
            v-for="saleAttr in saleAttrList"
            :key="saleAttr.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addSaleAttr"
          style="margin-left: 10px"
          :disabled="saleAttrList.length === 0"
          >添加销售属性</el-button
        >
        <el-table border style="width: 100%" :data="spuList.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="spuName" label="属性名">
            <template slot-scope="{ row }">
              <span>{{ row.saleAttrName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="spuValue" label="属性值名称列表">
            <template slot-scope="{ row, $index }">
              <el-tag
                v-for="saleAttrValue in row.spuSaleAttrValueList"
                :key="saleAttrValue.saleAttrValueName"
                closable
                size="small"
                style="margin-right: 5px"
                @close="handleClose(saleAttrValue, row)"
              >
                {{ saleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-button
                size="mini"
                @click="addSaleAttrValue(row, $index)"
                v-show="!row.showInput"
                >添加</el-button
              >
              <el-input
                v-show="row.showInput"
                class="inputSize"
                size="mini"
                v-model="saleAttrValueName"
                @blur="storeSaleAttrValue(row)"
                @keyup.enter.native="row.showInput = false"
                :ref="$index"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteSaleAttr(row, $index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSaleAttr">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "AddOrModifySpu",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      // 存储品牌信息
      trademarkList: [],
      // 要发送到服务端的数据（添加|修改spu）
      spuList: {
        // 三级分类ID
        category3Id: 0,
        // spu名称
        spuName: "",
        // spu描述
        description: "",
        // 品牌ID
        tmId: "",
        // 图片列表
        spuImageList: [],
        // 选择出来的销售属性的列表
        spuSaleAttrList: [],
      },
      // 存储销售属性
      saleAttrList: [],
      // 销售属性
      saleAttrName: "",
      // 销售属性值
      saleAttrValueName: "",
      // 照片墙图片列表
      spuImageList: [],
    };
  },
  // 接受父组件传过来的三级分类ID
  props: ["category3Id"],
  // 计算属性
  computed: {
    // 计算出销售属性选择框要默认呈现的文字
    showText() {
      if (this.saleAttrList.length > 0) {
        return `还有${this.saleAttrList.length}未选择`;
      } else {
        return "选完啦！";
      }
    },
  },
  methods: {
    // 获取品牌信息的函数
    async getTrademarkList() {
      const result = await this.$API.spu.reqTrademarkList();
      if (result.code === 200) {
        this.trademarkList = result.data;
      }
    },
    // 获取销售属性数据的函数
    async getSaleAttrList() {
      const result = await this.$API.spu.reqSaleAttrList();
      if (result.code === 200) {
        this.saleAttrList = result.data;
        // 初始化未选择出来的销售属性
        this.saleAttrList = this.saleAttrList.filter((item) => {
          return this.spuList.spuSaleAttrList.every((elm) => {
            if (item.name !== elm.saleAttrName) {
              return item;
            }
          });
        });
      }
    },
    // 删除图片的回调
    handleRemove(file) {
      // file 删除图片的信息
      this.spuImageList = this.spuImageList.filter(
        (item) => item.name !== file.name
      );
    },
    // 点击图片放大的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功的回调
    handleSuccess(_, fileList) {
      if (fileList.response.code === 200) {
        this.spuImageList.push(fileList);
      }
    },
    // 添加销售属性
    addSaleAttr() {
      if (!this.saleAttrName) {
        this.$message({
          message: "请选择销售属性",
          type: "warning",
        });
        return;
      }
      // 得到选出来的销售属性所对应的id
      const id = this.saleAttrList.find(
        (item) => item.name === this.saleAttrName
      ).id;
      // 将选出来的销售属性添加到spuSaleAttrList
      this.spuList.spuSaleAttrList.push({
        baseSaleAttrId: id,
        saleAttrName: this.saleAttrName,
        spuSaleAttrValueList: [],
        // 判断要显示input框还是按钮的属性
        showInput: false,
      });
      // 将选出来的销售属性从saleAttrList中移除
      this.saleAttrList = this.saleAttrList.filter(
        (item) => item.name !== this.saleAttrName
      );
      // 清空选出来的销售属性
      this.saleAttrName = "";
    },
    // 添加销售属性值
    addSaleAttrValue(row, index) {
      // 显示input文本框
      row.showInput = true;
      // 文本框自动聚焦
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 当文本框失去焦点后按下回车键后，将属性值存储起来
    storeSaleAttrValue(row) {
      // 判断输入的文字是否合法
      if (!this.saleAttrValueName) {
        // 弹出警告
        this.$message({
          message: "属性值不能为空",
          type: "warning",
        });
        return;
      }
      // 判断输入的属性值是否已经存在
      const result = row.spuSaleAttrValueList.some(
        (item) => item.saleAttrValueName === this.saleAttrValueName
      );
      if (result) {
        // 弹出警告
        this.$message({
          message: "属性值已经存在了",
          type: "warning",
        });
        return;
      }
      // 合法，则隐藏文本框，并将属性值存储起来
      row.showInput = false;
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: this.saleAttrValueName,
      }); 
      // 清空文本框
      this.saleAttrValueName = "";  
    },
    // 点击tag ×号的回调
    handleClose(tag, row) {
      // 删除掉点击的属性值
      row.spuSaleAttrValueList = row.spuSaleAttrValueList.filter(
        (item) => item.saleAttrValueName !== tag.saleAttrValueName
      );
    },
    // 点击删除当前属性
    deleteSaleAttr(row, index) {
      // 删除当前属性
      this.spuList.spuSaleAttrList.splice(index, 1);
      // 并将其重新放回saleAttrList中
      this.saleAttrList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        name: row.saleAttrName,
      });
    },
    // 取消添加|修改spu
    cancel() {
      // 自定义事件，隐藏增加|修改的卡片，展示spu列表的卡片
      this.$emit("updataShowCard");
      // 同时将data的数据重置成初始状态
      Object.assign(this.$data, this.$options.data());
      // 清空照片墙
      this.$refs.upload.clearFiles();
    },
    // 保存新增|修改的spu
    async saveSaleAttr() {
      const { spuName, description } = this.spuList;
      if (!spuName || !description || this.spuImageList.length === 0) {
        this.$message({
          message: "SPU名称、SPU描述和SPU图片不能为空",
          type: "warning",
        });
        return;
      }
      // 整合数据
      this.spuList.category3Id = this.category3Id;
      this.spuList.spuImageList = this.spuImageList;
      this.spuList.spuImageList.forEach((item) => {
        this.$set(item, "imgName", item.imgName ? item.imgName : item.name);
        this.$set(
          item,
          "imgUrl",
          item.imgUrl ? item.imgUrl : item.response.data
        );
      });
      // 发送请求
      try {
        await this.$API.spu.reqAddOrModifySpu(this.spuList);
        // 弹出成功的提示框
        this.$message({
          message: "保存成功",
          type: "success",
        });
        // 保存成功，跳转回展示spu列表的卡片
        this.$emit("updataShowCard", 1, this.spuList.id);
        // 同时将data的数据重置成初始状态
        Object.assign(this.$data, this.$options.data());
        // 清空照片墙
        this.$refs.upload.clearFiles();
      } catch (error) {
        this.$message({
          message: "保存失败",
          type: "error",
        });
      }
    },
    // 点击修改，初始化数据
    async initSpuList(row) {
      const result = await this.$API.spu.reqSaleAttrInfo(row.id);
      if (result.code === 200) {
        this.spuList = result.data;
        this.spuList.spuSaleAttrList.forEach((item) => {
          this.$set(item, "showInput", false);
        });
        this.saleAttrList = this.saleAttrList.filter((item) => {
          return this.spuList.spuSaleAttrList.every((elm) => {
            if (item.name !== elm.saleAttrName) {
              return item;
            }
          });
        });
      }
    },
    // 点击修改时，初始化照片墙
    async initSpuImageList(row) {
      const result = await this.$API.spu.reqSpuImageList(row.id);
      if (result.code === 200) {
        this.spuImageList = result.data;
        // 响应式添加 name 跟 url，照片墙是看这两个数据的
        this.spuImageList.forEach((item) => {
          this.$set(item, "name", item.imgName);
          this.$set(item, "url", item.imgUrl);
        });
      }
    },
  },
};
</script>

<style>
.inputSize {
  width: 90px;
}
</style>